using System;
using System.Collections.Generic;
using System.Text;
using LngT.Interfaces;
using LngT.Interfaces.UserRoles;
using LngT.User;
using LngT.Interfaces.DBUserRoles;
using LngT.DB;

namespace LngT.Impl
    {
    [Serializable]
    public class SessionManager: MarshalByRefObject, ISessionManager
        {
        public SessionManager() 
            {
            //
            }

        private IUserRole _usrPrivileges = new DefaultUserRole( null );

        public IController AddDatabase( string name, string userName, string password )
            {
            if( !_usrPrivileges.CanAddDatabases() )
                throw new AuthenticationException();

            IDatabase db = Database.AddDatabase( name, new DBUser( 0, userName, password, new DBAdminRole(null) ));
            IController cntr = new Controller( db );
            return cntr;
            }

        public bool RemoveDatabase( string name )
            {
            if( !_usrPrivileges.CanRemoveDatabases() )
                throw new AuthenticationException();

            return Database.RemoveDatabase( name );
            }

        public List<string> GetDatabaseList()
            {
            if( !_usrPrivileges.CanGetDatabaseList() )
                throw new AuthenticationException();

            return Database.GetDatabaseList();
            }

        public IController GetDatabase( string name )
            {
            //no access restriction for this
            IDatabase db =Database.GetDatabase( name );
            IController cntr = new Controller(db);

            return cntr;
            }

        public bool Authenticate( string userName, string password )
            {
            IUserRole newPrivileges = UserManager.Instance.GetUserPrivileges( userName, password );
            if( newPrivileges != null )
                {
                _usrPrivileges = newPrivileges;
                return true;
                }
            return false;
            }

        public void AddUser( string userName, string password, IUserRole privileges )
            {
            if( !_usrPrivileges.CanAddUsers())
                throw new AuthenticationException();

            UserManager.Instance.AddUser( userName, password, privileges );
            }

        public bool RemoveUsers( string userName )
            {
            if( !_usrPrivileges.CanRemoveUsers() )
                throw new AuthenticationException();

            return UserManager.Instance.RemoveUser( userName );
            }

        public List<string> GetUserList()
            {
            if( !_usrPrivileges.CanAddUsers() )
                throw new AuthenticationException();

            return UserManager.Instance.GetUserList();
            }

        }
    }
